package com.kingmed.kmss.framework.feign.client.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.kingmed.kmss.common.dto.admin.sys.SysMsgCreateDTO;
import com.kingmed.kmss.common.dto.admin.sys.SysMsgDTO;
import com.kingmed.kmss.common.dto.admin.ums.*;
import com.kingmed.kmss.common.enums.admin.OrgLevel;
import com.kingmed.kmss.common.exception.InternalApiException;
import com.kingmed.kmss.common.qc.admin.AdminQC;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.admin.SysBpmnConfigVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CommonAdminFeignServiceFacade {

    @Autowired
    private CommonAdminFeignService remoteFeignService;


    /**
     * 获得用户所在组织的管理部门的组织ID
     * 子公司， 大区， 集团
     *
     * @param userId
     * @return
     */
    public Long getManageOrgId(String userId) {
        Long userKeyId = getUserIdByName(userId);
        CommonResponse<OrganizationTileDTO> response = remoteFeignService.getGroupRegionBranchByAdminId(userKeyId);
        if (response.getCode() == HttpStatus.HTTP_UNAUTHORIZED || BeanUtil.isEmpty(response.getData())) {
            return null;
        }
        OrganizationTileDTO org = response.getData();

        Long orgId;
        if (org.getSubCompanyId() != null) {
            orgId = org.getSubCompanyId();
        } else if (org.getRegionId() != null) {
            orgId = org.getRegionId();
        } else {
            orgId = org.getGroupId();
        }
        return orgId;
    }

    /**
     * 获得用户所在组织的管理部门的组织类型
     * 3=子公司， 2=大区， 1=集团
     *
     * @param userId
     * @return
     */
    public Integer getManageOrgType(String userId) {
        log.debug("getManageOrgType-getUserIdByName");
        Long userKeyId = getUserIdByName(userId);

        log.debug("getManageOrgType-getGroupRegionBranchByAdminId");

        CommonResponse<OrganizationTileDTO> response = (CommonResponse<OrganizationTileDTO>) remoteFeignService.getGroupRegionBranchByAdminId(userKeyId);
        if (response.getCode() == HttpStatus.HTTP_UNAUTHORIZED || response.getData() == null) {
            return null;
        }
        OrganizationTileDTO org = response.getData();

        log.debug("getManageOrgType-calcOrg");
        Integer orgType;
        if (org.getSubCompanyId() != null) {
            orgType = OrgLevel.BRANCH.getCode();
        } else if (org.getRegionId() != null) {
            orgType = OrgLevel.REGION.getCode();
        } else {
            orgType = OrgLevel.GROUP.getCode();
        }


        log.debug("getManageOrgType-return");
        return orgType;
    }

    /**
     * 用户ID查上级组织部门信息
     *
     * @param userId
     * @return
     */
    public List<OrganizationDTO> getParentUpByUserId(Long userId) {
        log.debug("getParentUpByUserId: " + String.valueOf(userId));

        CommonResponse<List<OrganizationDTO>> response = remoteFeignService.getParentUpByAdminId(userId);

        if (response.getCode() == HttpStatus.HTTP_UNAUTHORIZED || BeanUtil.isEmpty(response.getData())) {
            return new ArrayList<>();
        }

        return response.getData();
    }


    public OrganizationDTO queryOrgById(Long orgId) {

        return remoteFeignService.queryOrgById(orgId);
    }

    public String getUserRealName(String userId) {

        log.debug("getUserRealName: " + userId);

        AdminQC userQC = new AdminQC();
        userQC.setUsername(userId);
        CommonResponse<AdminDTO> response = remoteFeignService.getByUsername(userId);
        if (response.getData() != null) {
            return response.getData().getNickName();
        }

        log.error("无法获得用户的真实名称: " + userId);
        return userId;
    }

    public Long getUserIdByName(String userName) {
        AdminQC userQC = new AdminQC();
        userQC.setUsername(userName);
        CommonResponse<AdminDTO> response = remoteFeignService.getByUsername(userName);
        if (response.getData() != null) {
            return response.getData().getId();
        }

        return -1L;
    }

    /**
     * 根据子公司或大区属性筛选出角色中的用户
     *
     * @param groupKey
     * @param orgType
     * @param parentOrgId
     * @return
     */
    public List<String> getRoleUsersByOrg(String groupKey, int orgType, String parentOrgId) {
        BpmnQueryDTO param = new BpmnQueryDTO();
        param.setGroupKey(groupKey);
        List<String> users = new ArrayList<String>();

        CommonResponse<List<BpmnMembershipDTO>> response = remoteFeignService.queryList(param);
        if (response.getData() == null) {
            return users;
        }

        Long parentOrgIdStr = Long.valueOf(parentOrgId);

        if (orgType == OrgLevel.BRANCH.getCode()) {
            users = response.getData().stream().filter(d -> (parentOrgIdStr.equals(d.getAdminBranchId())))
                    .map(BpmnMembershipDTO::getUsername).collect(Collectors.toList());
        } else if (orgType == OrgLevel.REGION.getCode()) {
            users = response.getData().stream().filter(d -> (parentOrgIdStr.equals(d.getAdminRegionId())))
                    .map(BpmnMembershipDTO::getUsername).collect(Collectors.toList());
        } else {
            log.error("getRoleUsers(): 无法找到审批用户. {}/{}/{}", groupKey, orgType, parentOrgId);
        }
        return users;
    }

    /**
     * 根据子公司或大区或者集团属性筛选出角色中的用户
     *
     */
    public List<String> getRoleUsersBaseOnOrg(String groupKey, int orgType, String parentOrgId) {
        BpmnQueryDTO param = new BpmnQueryDTO();
        param.setGroupKey(groupKey);
        List<String> users = new ArrayList<String>();

        CommonResponse<List<BpmnMembershipDTO>> response = remoteFeignService.queryList(param);
        if (response.getData() == null) {
            return users;
        }

        Long parentOrgIdStr = Long.valueOf(parentOrgId);

        if (orgType == OrgLevel.BRANCH.getCode()) {
            users = response.getData().stream().filter(d -> (parentOrgIdStr.equals(d.getAdminBranchId())))
                    .map(BpmnMembershipDTO::getUsername).collect(Collectors.toList());
        } else if (orgType == OrgLevel.REGION.getCode()) {
            users = response.getData().stream().filter(d -> (parentOrgIdStr.equals(d.getAdminRegionId())))
                    .map(BpmnMembershipDTO::getUsername).collect(Collectors.toList());
        } else if (orgType == OrgLevel.GROUP.getCode()) {
            users = response.getData().stream().map(BpmnMembershipDTO::getUsername).collect(Collectors.toList());
        }else {
            log.error("getRoleUsers(): 无法找到审批用户. {}/{}/{}", groupKey, orgType, parentOrgId);
        }
        return users;
    }

    /**
     * 返回审批角色中的用户
     *
     * @param groupKey
     * @param orgType
     * @param parentOrgId
     * @return
     */
    public List<String> getRoleUsers(String groupKey, int orgType, String parentOrgId) {
        BpmnQueryDTO param = new BpmnQueryDTO();
        param.setGroupKey(groupKey);
        List<String> users = new ArrayList<String>();

        CommonResponse<List<BpmnMembershipDTO>> response = remoteFeignService.queryList(param);
        if (response.getData() == null) {
            return users;
        }

        users = response.getData().stream().map(BpmnMembershipDTO::getUsername).collect(Collectors.toList());
        return users;
    }

    public AdminDTO getUserByUserName(String userName) {
        AdminQC userQC = new AdminQC();
        userQC.setUsername(userName);
        CommonResponse<List<AdminDTO>> response = remoteFeignService.queryByCondition(userQC);
        if (response.getData() != null && response.getData().size() > 0) {
            return response.getData().get(0);
        }

        return null;
    }

    public AdminDTO getUserByUserNum(String userNum) {
        AdminQC userQC = new AdminQC();
        userQC.setEmployeeNum(userNum);
        CommonResponse<List<AdminDTO>> response = remoteFeignService.queryByCondition(userQC);
        if (response.getData() != null && response.getData().size() > 0) {
            return response.getData().get(0);
        }
        return null;
    }

    /**
     * 根据ID查询用户信息
     *
     * @param id
     * @return
     */
    public AdminDTO loadById(Long id) {
        log.info("调用admin工程根据ID查询用户信息接口，入参[id]: {}", id);
        try {
            CommonResponse<AdminDTO> response = remoteFeignService.loadById(id);
            log.info("调用admin工程根据ID查询用户信息接口成功，出参：{}", response);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据ID查询用户信息接口异常", e);
        }
        return null;
    }


    public OrganizationDTO getOrgName(Long orgId) {
        log.info("getOrgName，入参[id]: {}", orgId);
        try {
            OrganizationDTO org = remoteFeignService.queryOrgById(orgId);
            log.info("getOrgName，出参：{}", org);
            return org;

        } catch (Exception e) {
            log.error("getOrgName接口异常", e);
        }
        return null;
    }

    /**
     * 根据人员id（adminId）获取所属集团、大区、子公司平铺
     *
     * @param adminId
     * @return
     */
    public OrganizationTileDTO getGroupRegionBranchByAdminId(Long adminId) {
        log.info("调用admin工程根据人员id（adminId）获取所属集团、大区、子公司平铺，入参[branchId]: {}", adminId);
        try {
            CommonResponse<OrganizationTileDTO> response = remoteFeignService.getGroupRegionBranchByAdminId(adminId);
            log.info("调用admin工程根据人员id（adminId）获取所属集团、大区、子公司平铺查询接口成功，出参：{}", response);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据人员id（adminId）获取所属集团、大区、子公司平铺接口异常", e);
        }
        return null;
    }

    /**
     * KMCS子公司名称及代码详情
     */
    public UmsKmcsOrgDTO kmcsOrgDetail(String orgId) {
        try {
            CommonResponse<UmsKmcsOrgDTO> response = remoteFeignService.kmcsOrgDetail(orgId);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据人员id（adminId）获取所属集团、大区、子公司平铺接口异常", e);
        }
        return new UmsKmcsOrgDTO();
    }

    /**
     * KMCS子公司名称及代码详情
     */
    public List<UmsKmcsOrgDTO> kmcsOrgList(Integer level) {
        try {
            CommonResponse<List<UmsKmcsOrgDTO>> response = remoteFeignService.kmcsOrgList(level);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据人员id（adminId）获取所属集团、大区、子公司平铺接口异常", e);
        }
        return new ArrayList<>();
    }

    /**
     * 根据用户ID批量查用户
     */
    public List<AdminDTO> getUsersByIds(List<String> userIds) {
        try {
            CommonResponse<List<AdminDTO>> response = remoteFeignService.queryBatchByEmployee(userIds);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据人员id（adminId）获取所属集团、大区、子公司平铺接口异常", e);
        }
        return new ArrayList<>();
    }

    /**
     * 根据用户ID批量查用户-只查员工信息，不附带任何其它信息
     */
    public List<AdminDTO> queryBatchByAdminIdList(List<String> userIds) {
        try {
            CommonResponse<List<AdminDTO>> response = remoteFeignService.queryBatchByAdminIdList(userIds);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据用户ID批量查用户接口异常", e);
        }
        return new ArrayList<>();
    }

    /**
     * 根据用户ID查用户
     */
    public AdminDTO getUserById(String userId) {
        List<String> userIds = new ArrayList<String>();
        userIds.add(userId);

        List<AdminDTO> users = getUsersByIds(userIds);
        if (CollUtil.isNotEmpty(users)) {
            return users.get(0);
        }
        return null;
    }

    /**
     * 发送系统消息
     *
     * @param msg
     * @return
     */
    public Boolean sendMsg(SysMsgCreateDTO msg) {
        log.info("调用admin工程接口，入参[msg]: {}", msg);
        try {
            CommonResponse<Boolean> response = remoteFeignService.createMsg(msg);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    /**
     * 按业务条件将相关消息状态设置为已读
     *
     * @param msg
     * @return
     */
    public Boolean markMsgAsReadForBiz(SysMsgDTO msg) {
        log.info("调用admin工程接口，入参[msg]: {}", msg);
        try {
            CommonResponse<Boolean> response = remoteFeignService.markMsgAsReadForBusiness(msg);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    /**
     * 批量发送系统消息
     *
     * @param msgList
     * @return
     */
    public Boolean createBatchMsg(List<SysMsgCreateDTO> msgList) {
        log.info("调用admin工程接口，入参[msgList]: {}", msgList);
        try {
            CommonResponse<Boolean> response = remoteFeignService.createBatchMsg(msgList);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    /**
     * 返回角色中的用户DTO
     *
     * @param groupKey
     * @return
     */
    public List<BpmnMembershipDTO> getRoleUsers(String groupKey) {
        log.info("调用admin工程获取角色中所有用户接口，入参: {}", groupKey);
        try {
            BpmnQueryDTO param = new BpmnQueryDTO();
            param.setGroupKey(groupKey);
            CommonResponse<List<BpmnMembershipDTO>> response = remoteFeignService.queryList(param);
            log.info("调用admin工程获取角色中所有用户接口成功，出参：{}", response);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程获取角色中所有用户接口异常", e);
        }
        return null;
    }

    /**
     * 获取本部门及下属所有部门（有parent关系的所有子部门）
     *
     * @param orgId
     * @return
     */
    public String getOrgAndChild(Long orgId) {
        return remoteFeignService.getOrgAndChild(orgId);
    }

    public List<AdminDTO> fuzzyQueryAllByName(String username) {
        try {
            CommonResponse<List<AdminDTO>> response = remoteFeignService.fuzzyQueryAllByName(username);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程:模糊查询员工信息接口异常", e);
        }
        return null;
    }

    public String getUserDirectLeader(String username) {
        log.debug("getUserDirectLeader: " + username);

        CommonResponse<AdminDTO> response = remoteFeignService.getByUsername(username);
        if (response.getData() != null) {
            return response.getData().getDirectLeader();
        }

        log.error("无法获得用户的直属上线: " + username);
        return null;
    }

    public AdminDTO queryUserById(String id) {
        log.info("调用admin-根据ID查询用户信息queryUserById接口，入参[id]: {}", id);
        try {
            CommonResponse<AdminDTO> response = remoteFeignService.getUserById(id);
            log.info("调用admin-根据ID查询用户信息queryUserById接口成功，出参：{}", response);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin-根据ID查询用户信息queryUserById接口异常", e);
        }
        return null;
    }

    /**
     * 组织ID获取全部子公司：有权限看到的所有子公司
     *
     * @param orgId
     * @return
     */
    public List<OrganizationDTO> getBranchesByOrgId(Long orgId) {
        log.info("调用admin工程接口，入参[orgId]: {}", orgId);
        try {
            CommonResponse<List<OrganizationDTO>> response = remoteFeignService.getBranchesByOrgId(orgId);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    /**
     * 根据adminId获取全部子公司：有权限看到的所有子公司
     *
     * @param adminId
     * @return
     */
    public List<OrganizationDTO> getBranchesByAdminId(Long adminId) {
        log.info("调用admin工程接口，入参[adminId]: {}", adminId);
        try {
            CommonResponse<List<OrganizationDTO>> response = remoteFeignService.getBranchesByAdminId(adminId);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    /**
     * 通过子公司名称查询子公司信息, 通过大区名称查询大区信息
     *
     * @param branchName
     * @param regionName
     * @return
     */
    public List<OrganizationDTO> getBranchesByOrgId(String branchName,
                                                    String regionName) {
        log.info("调用admin工程接口，入参[branchName]: {},[regionName]: {}", branchName, regionName);
        try {
            CommonResponse<List<OrganizationDTO>> response = remoteFeignService.getOrgByName(branchName,
                    regionName);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }


    /**
     * 外部调用-根据员工号获取相关的信息（角色权限），用于对外接口的数据权限控制
     *
     * @param adminLoginDto
     * @return
     */
    public AdminAuthDTO loadAdminAuthDtoByUsernameNew(AdminLoginDTO adminLoginDto) {
        log.info("调用admin工程接口，入参[username]: {}", adminLoginDto.getUsername());
        try {
            CommonResponse<AdminAuthDTO> response = remoteFeignService.loadAdminAuthDtoByUsernameNew(adminLoginDto);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    public LoginUserDTO loadAdminAuthDtoByUsernameNew(String userName) {
        if (StrUtil.isBlank(userName)) {
            return null;
        }
        AdminLoginDTO adminLoginDTO = new AdminLoginDTO(userName, "pwd", null);
        AdminAuthDTO adminAuthDTO = loadAdminAuthDtoByUsernameNew(adminLoginDTO);
        if (adminAuthDTO == null) {
            return null;
        }
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        BeanUtil.copyProperties(adminAuthDTO, loginUserDTO);
        return loginUserDTO;
    }


    /**
     * 根据orgId获取子公司信息-todo 有bug
     *
     * @param orgId
     * @return
     */
    public OrganizationDTO queryBranch(Long orgId) {
        log.info("调用admin工程根据orgId获取子公司信息，入参[orgId]: {}", orgId);
        try {
            CommonResponse<OrganizationDTO> response = remoteFeignService.getBranch(orgId);
            log.info("调用admin工程字典查询接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据orgId获取子公司信息接口异常", e);
        }
        return null;
    }

    /**
     * 根据orgIds批量获取子公司信息
     *
     * @param orgIds
     * @return
     */
    public Map<Long, OrganizationDTO> getOrgByIds(List<Long> orgIds) {
        log.info("调用admin工程根据orgIds批量获取子公司信息，入参[orgIds]: {}", orgIds);
        try {
            CommonResponse<Map<Long, OrganizationDTO>> response = remoteFeignService.getOrgByIds(orgIds);
            log.info("调用admin工程字典查询接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据orgIds批量获取子公司信息接口异常", e);
        }
        return null;
    }

    /**
     * 根据所属子公司id获取所属大区
     *
     * @param branchId
     * @return
     */
    public OrganizationDTO getRegionByBranchId(Long branchId) {
        log.info("调用admin工程根据所属子公司id获取所属大区，入参[branchId]: {}", branchId);
        try {
            CommonResponse<OrganizationDTO> response = remoteFeignService.getRegionByBranchId(branchId);
            log.info("调用admin工程根据所属子公司id获取所属大区查询接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程根据所属子公司id获取所属大区信息接口异常", e);
        }
        return null;
    }

    /**
     * 查询用户详情
     *
     * @param username
     * @return
     */
    public AdminDTO getByUsername(String username) {
        log.info("调用admin工程接口，入参[username]: {}", username);
        try {
            CommonResponse<AdminDTO> response = remoteFeignService.getByUsername(username);
            log.info("调用admin工程接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }


    public List<AdminDTO> listByUsername(List<String> usernameList) {
        try {
            CommonResponse<List<AdminDTO>> response = remoteFeignService.listByUsername(usernameList);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
            throw new InternalApiException("根据用户名获取员工信息失败!,详情：" + response);
        } catch (Exception e) {
            throw new InternalApiException("根据员工工号获取员工信息失败!");
        }
    }

    /**
     * 获取所有大区
     *
     * @return
     */
    public List<OrganizationDTO> getRegions() {
        log.info("调用admin工程接口");
        try {
            CommonResponse<List<OrganizationDTO>> response = remoteFeignService.getRegions();
            log.info("调用admin工程接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    /**
     * 获取所有子公司
     *
     * @return
     */
    public List<OrganizationDTO> getAllBranch() {
        log.info("调用admin工程接口");
        try {
            CommonResponse<List<OrganizationDTO>> response = remoteFeignService.getAllBranch();
            log.info("调用admin工程接口成功，出参：{}", response);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
        } catch (Exception e) {
            log.error("调用admin工程接口异常", e);
        }
        return null;
    }

    public String genNextVal(String bizKey, Integer len, Integer step) {
        try {
            CommonResponse<String> response = remoteFeignService.genNextVal(bizKey, len, step);
            if (HttpStatus.HTTP_OK == response.getCode()) {
                return response.getData();
            }
            throw new InternalApiException("admin service: genNextVal调用失败!");
        } catch (Exception e) {
            throw new InternalApiException("生成流水号失败!");
        }
    }


    public List<UmsKmcsOrgDTO> listByLevels(List<Integer> levels) {
        try {
            CommonResponse<List<UmsKmcsOrgDTO>> response = remoteFeignService.listByLevels(levels);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
            throw new InternalApiException("获取子公司信息失败!,详情：" + response);
        } catch (Exception e) {
            throw new InternalApiException("获取子公司信息失败!");
        }
    }

    public List<AdminDTO> listEmployeeNum(List<String> employeeNumList) {
        try {
            CommonResponse<List<AdminDTO>> response = remoteFeignService.listEmployeeNum(employeeNumList);
            if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
                return response.getData();
            }
            throw new InternalApiException("根据员工工号获取员工信息失败!,详情：" + response);
        } catch (Exception e) {
            log.error("根据员工工号获取员工信息失败!", e);
            throw new InternalApiException("根据员工工号获取员工信息失败!");
        }
    }

    public SysBpmnConfigVO getBpmnConfigByCompanyId(Long companyId) {
        CommonResponse<SysBpmnConfigVO> response = remoteFeignService.getBpmnConfigByCompanyId(companyId);
        if (org.springframework.http.HttpStatus.OK.value() == response.getCode()) {
            return response.getData();
        }
        throw new InternalApiException("获取流程审批配置失败：" + response);
    }

    //子公司，大区，集团，三选一
    public String getManageOrgNameByUsername(String username) {
        log.debug("getManageOrgType-getUserIdByName");

        //需要把username变成userid
        Long userId = getUserIdByName(username);

        log.debug("getManageOrgType-getGroupRegionBranchByAdminId");

        CommonResponse<OrganizationTileDTO> response = remoteFeignService.getGroupRegionBranchByAdminId(userId);
        if (response.getCode() == HttpStatus.HTTP_UNAUTHORIZED || response.getData() == null) {
            return null;
        }
        OrganizationTileDTO org = response.getData();

        log.debug("getManageOrgType-calcOrg");
        String orgName;
        if (org.getSubCompanyId() != null) {
            orgName = org.getSubCompanyName();
        } else if (org.getRegionId() != null) {
            orgName = org.getRegionName();
        } else {
            orgName = org.getGroupName();
        }
        log.debug("getManageOrgType-return");
        return orgName;
    }

    public OrganizationManageDTO getOrganizationManageByUserId(Long userId) {
        log.debug("getManageOrgType-getGroupRegionBranchByAdminId");

        CommonResponse<OrganizationTileDTO> response = remoteFeignService.getGroupRegionBranchByAdminId(userId);
        if (response.getCode() == HttpStatus.HTTP_UNAUTHORIZED || response.getData() == null) {
            return null;
        }
        OrganizationTileDTO org = response.getData();
        OrganizationManageDTO result = new OrganizationManageDTO();
        log.debug("getManageOrgType-calcOrg");
        if (org.getSubCompanyId() != null) {
            result.setId(org.getSubCompanyId());
            result.setName(org.getSubCompanyName());
            result.setKmcsCode(org.getSubCompanyCodeKmcs());
        } else if (org.getRegionId() != null) {
            result.setId(org.getRegionId());
            result.setName(org.getRegionName());
            result.setKmcsCode(org.getRegionCodeKmcs());
        } else {
            result.setId(org.getGroupId());
            result.setName(org.getGroupName());
            result.setKmcsCode(org.getGroupCodeKmcs());
        }
        log.debug("getManageOrgType-return");
        return result;
    }

}
